package repository

import (
	"database/sql"
	"fmt"
	"log"
	"todolist/internal/model"
)

type TodoRepository struct {
	db *sql.DB
}

func NewTodoRepository(db *sql.DB) *TodoRepository {
	return &TodoRepository{db: db}
}

func (r *TodoRepository) Create(task *model.Todo) error {
	log.Printf("Creating task with user_id: %d", task.UserID)
	
	// 先检查用户是否存在
	var exists bool
	err := r.db.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE id = ?)", task.UserID).Scan(&exists)
	if err != nil {
		log.Printf("Error checking user existence: %v", err)
		return err
	}
	if !exists {
		log.Printf("User with ID %d does not exist", task.UserID)
		return fmt.Errorf("user with ID %d does not exist", task.UserID)
	}
	
	result, err := r.db.Exec(
		"INSERT INTO tasks (title, description, completed, user_id) VALUES (?, ?, ?, ?)",
			task.Title,
			task.Description,
			task.Completed,
			task.UserID,
	)
	if err != nil {
		log.Printf("Error executing insert: %v", err)
		return err
	}

	id, err := result.LastInsertId()
	if err != nil {
		log.Printf("Error getting last insert ID: %v", err)
		return err
	}

	task.ID = int(id)
	log.Printf("Task created with ID: %d", id)
	return nil
} 